﻿using AME.Database;
using AME.Setting;
using SqlSugar;
using System.Configuration;
using System.Reflection;

namespace DbOperation
{
    public class CreateDB
    {
        public void CreateDatabase()
        {
            DbType dbType = (DbType)Enum.Parse(typeof(DbType), SettingExtensions.Configuration["DBConfig:DbType"] ?? throw new ConfigurationErrorsException("[DBConfig:DbType] error, please check appsettings.json"));
            string connectionString = SettingExtensions.Configuration["DBConfig:ConnectionStrings"] ?? throw new ConfigurationErrorsException("[DBConfig:ConnectionStrings] error, please check appsettings.json");

            var db = SqlClient.CreateSqlClinet(dbType, connectionString);

            //建库
            db.DbMaintenance.CreateDatabase();//达梦和Oracle不支持建库

            // 加载Model程序集
            Assembly externalAssembly = Assembly.Load("Model");
            // 查找建表实体
            var sugarTableAttribute = externalAssembly.GetTypes()
                .Where(t => t.GetCustomAttributes(typeof(SugarTable), true).Any())
                .ToList();
            //建表
            foreach (var table in sugarTableAttribute)
            {
                db.CodeFirst.InitTables(table);
            }

            //插入种子数据


        }

    }
}
